﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using System.Text;
using DP.Common;
using DP.Web.UI;

namespace CRM.Web.MessagingManage
{
    public partial class NoteSend : Common.PageBase
    {
        T_NOTE_MSG_BLL bll = new T_NOTE_MSG_BLL();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
            PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                tvOrgBinding();
                pageInit();
            }
        }

        private void pageInit()
        {
            this.txtUNAME.Text = _userLoginInfo.UserEntity.USERNAME;
        }

        #region 加载属性结构

        /// <summary>
        /// 加载树形结构图中的内容
        /// </summary>
        private void tvOrgBinding()
        {
            tvGhid.Nodes.Clear();
            TreeNode pNode = new TreeNode();
            pNode.Text = "收信人列表";
            pNode.ToolTip = "收信人列表";

            tvBusinessdivsionBinding(pNode);

            tvGhid.Nodes.Add(pNode);
            tvGhid.ExpandDepth = 1;
        }

        /// <summary>
        /// 加载事业部信息
        /// </summary>
        /// <param name="tn"></param>
        protected void tvBusinessdivsionBinding(TreeNode tn)
        {
            T_BUSINESSDIVISION_BLL dal = new T_BUSINESSDIVISION_BLL();
            List<T_BUSINESSDIVISION_Entity> list = dal.GetCache_T_BUSINESSDIVISION_List(this.Page);
            if (list != null)
            {
                foreach (T_BUSINESSDIVISION_Entity en in list)
                {
                    string text = String.Format("{0}", en.BUSINESSDIVISIONNAME);
                    TreeNode node = new TreeNode(text, "");
                    node.ImageUrl = "~/Images/Top/arrow.gif";
                    tvUserType(node, en.BUSINESSDIVISIONID.ToString());

                    node.Collapse();
                    if (node.ChildNodes.Count > 0)
                    {
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 用户类型   中心部门 = 0,市场部 = 1,供应商 = 2,经销商 = 3,服务商 = 4
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="businessID"></param>
        protected void tvUserType(TreeNode tn, string businessID)
        {
            //中心部门
            string text = String.Format("{0}", (UserType.中心部门).ToString());
            TreeNode node = new TreeNode(text, "");
            node.ImageUrl = "~/Images/Top/item.gif";
            tvDepartmentBinding(node, businessID);
            node.Collapse();

            if (node.ChildNodes.Count > 0)
            {
                tn.ChildNodes.Add(node);
            }
            //市场部
            text = String.Format("{0}", (UserType.市场部).ToString());
            node = new TreeNode(text, "");
            node.ImageUrl = "~/Images/Top/item.gif";
            tvMarketdepartmentBinding(node, businessID);
            node.Collapse();

            if (node.ChildNodes.Count > 0)
            {
                tn.ChildNodes.Add(node);
            }
            //供应商
            text = String.Format("{0}", (UserType.供应商).ToString());
            node = new TreeNode(text, "");
            node.ImageUrl = "~/Images/Top/item.gif";
            tvSupplierBinding(node, businessID);
            node.Collapse();

            if (node.ChildNodes.Count > 0)
            {
                tn.ChildNodes.Add(node);
            }
            //经销商
            text = String.Format("{0}", (UserType.经销商).ToString());
            node = new TreeNode(text, "");
            node.ImageUrl = "~/Images/Top/item.gif";
            tvDealerBinding(node, businessID);
            node.Collapse();

            if (node.ChildNodes.Count > 0)
            {
                tn.ChildNodes.Add(node);
            }
            //服务商
            text = String.Format("{0}", (UserType.服务商).ToString());
            node = new TreeNode(text, "");
            node.ImageUrl = "~/Images/Top/item.gif";
            tvServiceproviderBinding(node, businessID);
            node.Collapse();

            if (node.ChildNodes.Count > 0)
            {
                tn.ChildNodes.Add(node);
            }
        }

        /// <summary>
        /// 加载部门信息
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="businessID"></param>
        protected void tvDepartmentBinding(TreeNode tn, string businessID)
        {
            T_DEPARTMENT_BLL dal = new T_DEPARTMENT_BLL();
            List<T_DEPARTMENT_Entity> list = dal.GetPageItem_T_DEPARTMENT_List(this.Page).FindAll(p => p.BUSINESSDIVISIONID.ToString() == businessID);
            if (list != null)
            {
                foreach (T_DEPARTMENT_Entity en in list)
                {
                    string text = String.Format("{0}", en.DEPARTMENTNAME);
                    TreeNode node = new TreeNode(text, "");
                    node.ImageUrl = "~/Images/Top/item.gif";

                    tvAgentBinding(node, en.DEPARTMENTID.ToString());

                    node.Collapse();

                    if (node.ChildNodes.Count > 0)
                    {
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 市场部
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="businessID"></param>
        protected void tvMarketdepartmentBinding(TreeNode tn, string businessID)
        {
            T_MARKETDEPARTMENT_BLL dal = new T_MARKETDEPARTMENT_BLL();
            List<T_MARKETDEPARTMENT_Entity> list = dal.GetCache_T_MARKETDEPARTMENT_List(this.Page).FindAll(p => p.BUSINESSDIVISIONID.ToString() == businessID);
            if (list != null)
            {
                foreach (T_MARKETDEPARTMENT_Entity en in list)
                {
                    string text = String.Format("{0}", en.MARKETDEPARTMENTNAME);
                    TreeNode node = new TreeNode(text, "");
                    node.ImageUrl = "~/Images/Top/item.gif";

                    tvAgentBinding(node, en.MARKETDEPARTMENTID.ToString());

                    node.Collapse();

                    if (node.ChildNodes.Count > 0)
                    {
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 供应商
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="businessID"></param>
        protected void tvSupplierBinding(TreeNode tn, string businessID)
        {
            T_SUPPLIER_BLL dal = new T_SUPPLIER_BLL();
            List<T_SUPPLIER_Entity> list = dal.GetCache_T_SUPPLIER_List(this.Page).FindAll(p => p.BUSINESSDIVISIONID.ToString() == businessID);
            if (list != null)
            {
                foreach (T_SUPPLIER_Entity en in list)
                {
                    string text = String.Format("{0}", en.SUPPLIERNAME);
                    TreeNode node = new TreeNode(text, "");
                    node.ImageUrl = "~/Images/Top/item.gif";

                    tvAgentBinding(node, en.SUPPLIERID.ToString());

                    node.Collapse();

                    if (node.ChildNodes.Count > 0)
                    {
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 经销商
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="businessID"></param>
        protected void tvDealerBinding(TreeNode tn, string businessID)
        {
            T_DEALER_BLL dal = new T_DEALER_BLL();
            List<T_DEALER_Entity> list = dal.GetCache_T_DEALER_List(this.Page).FindAll(p => p.BUSINESSDIVISIONID.ToString() == businessID);
            if (list != null)
            {
                foreach (T_DEALER_Entity en in list)
                {
                    string text = String.Format("{0}", en.DEALERNAME);
                    TreeNode node = new TreeNode(text, "");
                    node.ImageUrl = "~/Images/Top/item.gif";

                    tvAgentBinding(node, en.DEALERID.ToString());

                    node.Collapse();

                    if (node.ChildNodes.Count > 0)
                    {
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 服务商
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="businessID"></param>
        protected void tvServiceproviderBinding(TreeNode tn, string businessID)
        {
            T_SERVICEPROVIDER_BLL dal = new T_SERVICEPROVIDER_BLL();
            List<T_SERVICEPROVIDER_Entity> list = dal.GetCache_T_SERVICEPROVIDER_List(this.Page).FindAll(p => p.BUSINESSDIVISIONID.ToString() == businessID);
            if (list != null)
            {
                foreach (T_SERVICEPROVIDER_Entity en in list)
                {
                    string text = String.Format("{0}", en.SERVICEPROVIDERNAME);
                    TreeNode node = new TreeNode(text, "");
                    node.ImageUrl = "~/Images/Top/item.gif";

                    tvAgentBinding(node, en.SERVICEPROVIDERID.ToString());

                    node.Collapse();

                    if (node.ChildNodes.Count > 0)
                    {
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 加载座席信息
        /// </summary>
        /// <param name="tn"></param>
        /// <param name="departID"></param>
        protected void tvAgentBinding(TreeNode tn ,string departID)
        {
            T_USER_BLL dal = new T_USER_BLL();
            List<T_USER_Entity> list = dal.GetCache_T_USER_List(this.Page).FindAll(p => p.DEPARTMENTID.ToString() == departID);
            if (list != null)
            {
                foreach (T_USER_Entity en in list)
                {
                    if (list.Exists(delegate(T_USER_Entity oEntity) { if (oEntity.USERID == en.USERID) return true; else return false; }))
                    {
                        string text = String.Format(" {0}-{1}", en.USERID, en.USERNAME); ;
                        TreeNode node = new TreeNode(text, en.USERID.ToString());
                        node.ImageUrl = "~/Images/Top/Agent.gif";
                        tn.ChildNodes.Add(node);
                    }
                }
            }
        }

        #endregion

        /// <summary>
        /// Handles the Click event of the btnUpload control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string filepath = UploadFile(this.Page, ImportFile);
            string filename = GetFileName(filepath);
            if (string.IsNullOrEmpty(filepath))
            {
                PageHelper.ShowMessage(this.Page, "文件上传失败！");
                return;
            }

            btnOK.Enabled = true;
            txtFILENAME.Text = StaticConstant.UploadFilePath + "\\" + filename;
            lblFILENAME.Text = GetFileName(ImportFile.PostedFile.FileName);
        }

        /// <summary>
        /// 文件 上传方法
        /// </summary>
        /// <param name="page">当前页面</param>
        /// <param name="auc">上传控件</param>
        /// <returns>上传后的文件的服务器路径</returns>
        private string UploadFile(Page page, System.Web.UI.WebControls.FileUpload auc)
        {
            string temp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string filename = auc.PostedFile.FileName;
            filename = GetFileName(filename);

            string filepath = HttpContext.Current.Request.MapPath(StaticConstant.UploadFilePath);

            int index = filename.LastIndexOf('.');
            if (index != -1)
            {
                filename = filename.Insert(index, temp);
            }
            else
            {
                filename += temp;
            }

            string fullpath = string.Empty;
            if (filepath.LastIndexOf("\\") == filepath.Length - 1)
            {
                fullpath = filepath + filename;
            }
            else
            {
                fullpath = filepath + "\\" + filename;
            }

            try
            {
                auc.PostedFile.SaveAs(fullpath);
            }
            catch
            {
                fullpath = null;
            }
            return fullpath;
        }

        /// <summary>
        /// 在绝对路径中，获取Excel文件名
        /// </summary>
        /// <param name="input">需要导入的Excel绝对路径</param>
        /// <returns></returns>
        private string GetFileName(string input)
        {
            return input.Substring(input.LastIndexOf("\\") + 1);
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            long rel = 0;
            int nUserid = 0;
            bool bTrue = false;

            if (this.txtSUBJECTS.Text.Trim() == "")
            {
                PageHelper.ShowMessage(this.Page, "请输入消息主题！");
                return;
            }

            if (this.txtBODYS.Text.Trim() == "")
            {
                PageHelper.ShowMessage(this.Page, "请输入消息内容！");
                return;
            }

            T_NOTE_MSG_Entity entity;

            T_USER_BLL dal = new T_USER_BLL();
            T_USER_Entity UserEntity;

            string[] useridList = GetSelectedUserID().Split(';');

            for (int i = 0; i < useridList.Length; i++)
            {
                try
                {
                    nUserid = int.Parse(useridList[i].ToString());
                }
                catch { continue; }

                UserEntity = dal.GetCache_T_USER_EntityByKey(this.Page, nUserid);

                entity = new T_NOTE_MSG_Entity();

                entity.CONTENT = this.txtBODYS.Text.Trim();
                entity.FILES = this.lblFILENAME.Text;
                entity.STATUS = 0;//表示新消息
                entity.SUBJECT = this.txtSUBJECTS.Text.Trim();
                entity.FILEPATH = this.txtFILENAME.Text.Trim();

                entity.SEND_BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                entity.SEND_BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                entity.SEND_BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                entity.CREATETIME = DateTime.Now;
                entity.SENDID = _userLoginInfo.UserEntity.USERID.ToString();
                entity.SENDNAME = _userLoginInfo.UserEntity.USERNAME;

                entity.RECV_BUSINESSDIVISIONCODE = UserEntity.BUSINESSDIVISIONCODE;
                entity.RECV_BUSINESSDIVISIONID = UserEntity.BUSINESSDIVISIONID;
                entity.RECV_BUSINESSDIVISIONNAME = UserEntity.BUSINESSDIVISIONNAME;
                entity.RECVID = UserEntity.USERID.ToString();
                entity.RECVNAME = UserEntity.USERNAME;

                rel = bll.Insert(entity);
                bTrue = true;
            }

            if (!bTrue)
            {
                PageHelper.ShowMessage(this.Page, "请选择收信人！");
                return;
            }

            if (rel > 0)
            {
                PageHelper.ShowMessage(this.Page, "内部消息发送成功！");
            }
            else
            {
                PageHelper.ShowMessage(this.Page, "内部消息发送失改！");
            }  
        }

        /// <summary>
        /// 得到所有勾选的座席工号 
        /// </summary>
        /// <returns></returns>
        private string GetSelectedUserID()
        {
            StringBuilder sb = new StringBuilder();
            tvRecursiveValue(tvGhid.Nodes[0], sb);
            sb.Append(";");
            return sb.ToString();
        }

        private void tvRecursiveValue(TreeNode node, StringBuilder sb)
        {
            if (node.Checked)
            {
                if (sb.Length != 0)
                {
                    sb.Append(";");
                }
                if (node.Value.ToString() != "")
                {
                    sb.Append(node.Value.ToString());
                }
            }
            foreach (TreeNode subnode in node.ChildNodes)
            {
                tvRecursiveValue(subnode, sb);
            }
        }
    }
}
